package cn.easy.mortgage.web.app;

import cn.easy.base.web.BaseController;
import org.springside.modules.utils.mapper.JsonMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author caosk
 * @Description: 微信端基类控制器
 * @date 2015年6月2日 下午9:35:55
 */
public class AppBaseController extends BaseController {

    protected String getOpenId(HttpServletRequest request) {
        HttpSession session = request.getSession();
        return session.getAttribute("openId") == null ? null : session.getAttribute("openId").toString();
    }

    protected String getSessionAttr(HttpServletRequest request, String attr) {
        HttpSession session = request.getSession();
        return session.getAttribute(attr) == null ? null : session.getAttribute(attr).toString();
    }

    protected String toSelectJsonWithAll(Map<String, String> configMap, String allTitle) {
        List<Map<String, String>> selectList = toSelectList(configMap);

        Map<String, String> allSelectMap = new HashMap<>();
        allSelectMap.put("title", allTitle);
        selectList.add(0, allSelectMap);

        return JsonMapper.nonEmptyMapper().toJson(selectList);
    }

    protected String toSelectJsonWithAll(Map<String, String> configMap) {
        return toSelectJsonWithAll(configMap, "全部");
    }

    protected String toSelectJson(Map<String, String> configMap) {
        return JsonMapper.nonEmptyMapper().toJson(toSelectList(configMap));
    }

    private List<Map<String, String>> toSelectList(Map<String, String> configMap) {
        List<Map<String, String>> selectList = new ArrayList<>();
        for (Map.Entry<String, String> entry : configMap.entrySet()) {
            Map<String, String> courseTypeSelectMap = new HashMap<>();
            courseTypeSelectMap.put("title", entry.getValue());
            courseTypeSelectMap.put("value", entry.getKey());
            selectList.add(courseTypeSelectMap);
        }
        return selectList;
    }

    protected String getBasePath(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + request.getServletPath();
    }

    protected boolean isValidId(Integer id) {
        return id != null && id.intValue() > 0;
    }

}
